﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Warehouse;
using NewRetail.Application.Components.Warehouse.Entity;
using NewRetail.Application.Core;
using NewRetail.Application.Core.Entity;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("change-warehouse")]
    public class ChangeWarehouseController : BaseController<ChangeWarehouse, ChangeWarehousePagingDto>
    {
        private readonly IWarehouseGoodsService warehouseGoodsService;
        private readonly IChangeWarehouseService changeWarehouseService;

        public ChangeWarehouseController(
            IWarehouseGoodsService warehouseGoodsService,
            IChangeWarehouseService changeWarehouseService)
        {
            this.warehouseGoodsService = warehouseGoodsService;
            this.changeWarehouseService = changeWarehouseService;
        }

        protected override async Task<IQueryable<ChangeWarehouse>> FilterQueryPaging(DbContext db, IQueryable<ChangeWarehouse> query, ChangeWarehousePagingDto dto)
        {
            if (!string.IsNullOrWhiteSpace(dto.inWarehouseId))
            {
                query = query.Where(x => x.inWarehouseID == dto.inWarehouseId);
            }

            if (!string.IsNullOrWhiteSpace(dto.outWarehouseId))
            {
                query = query.Where(x => x.outWarehouseID == dto.outWarehouseId);
            }

            await Task.CompletedTask;
            return query;
        }

        public override async Task<ResponseEntity<PagedResultDto<ChangeWarehouse>>> QueryPaging([FromBody] ChangeWarehousePagingDto dto)
        {
            var res = await base.QueryPaging(dto);

            if (res.Data?.Items?.Any() ?? false)
            {
                res.Data.Items = await this.changeWarehouseService.AttachWarehouseInfo(res.Data.Items.ToArray());
            }

            return res;
        }

        [HttpPost("save-multiple")]
        public async Task<ResponseEntity<ChangeWarehouse[]>> SaveMultiple([FromBody] ReceiptNoItemsDto<ChangeWarehouse> data)
        {
            var res = await this.Repo.SaveReceiptItems(this.HttpContext.RequestServices, data, "DB");
            return new ResponseEntity<ChangeWarehouse[]>().SetData(res.Items);
        }

        [HttpPost("query-by-receipt-no")]
        public async Task<ResponseEntity<ChangeWarehouse[]>> QueryByReceiptNo([FromBody] ReceiptNoDto dto)
        {
            dto.Should().NotBeNull();
            dto.receiptNo.Should().NotBeNullOrEmpty();
            var query = this.SingleStoreService.ApplyToQueryable(this.Repo);
            var data = await query.Where(x => x.receiptNo == dto.receiptNo).ToArrayAsync();

            return new ResponseEntity<ChangeWarehouse[]>().SetData(data);
        }
    }
}
